package org.mq.mymq.common.remote;

import org.mq.mymq.common.cache.NameServerSyncFutureManager;

import java.util.concurrent.*;

/**
 * @ClassName SyncFuture
 * @Description
 * @Author jiarong_ye
 * @Date 2025/6/26 11:33
 * @Version 1.0
 */
public class SyncFuture implements Future {
    /**
     * 远程rpc返回的数据内容
     */
    private String msgId;
    private  Object response;
    private CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return response != null;
    }

    @Override
    public Object get() throws InterruptedException, ExecutionException {
        try {
            countDownLatch.await();
        } finally {
            NameServerSyncFutureManager.remove(msgId);
        }
        return response;
    }

    @Override
    public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        try {
            countDownLatch.await(timeout, unit);
        } finally {
            NameServerSyncFutureManager.remove(msgId);
        }
        return response;
    }

    public Object getResponse() {
        return response;
    }

    public void setResponse(Object response) {
        this.response = response;
        countDownLatch.countDown();
    }

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public String getMsgId() {
        return msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }
}
